/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.task;

import cn.easyplatform.contexts.ListContext;
import cn.easyplatform.contexts.RecordContext;
import cn.easyplatform.contexts.WorkflowContext;
import cn.easyplatform.entities.beans.table.TableBean;
import cn.easyplatform.entities.helper.EventLogic;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.ActionRequestMessage;
import cn.easyplatform.messages.response.FieldsUpdateResponseMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.messages.vos.ActionVo;
import cn.easyplatform.type.Constants;
import cn.easyplatform.type.EntityType;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.util.MessageUtils;
import cn.easyplatform.util.RuntimeUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class ActionCmd extends AbstractCommand<ActionRequestMessage> {

    /**
     * @param req
     */
    public ActionCmd(ActionRequestMessage req) {
        super(req);
    }

    @Override
    public IResponseMessage<?> execute(CommandContext cc) {
        ActionVo av = req.getBody();
        WorkflowContext ctx = cc.getWorkflowContext();
        RecordContext rc = ctx.getRecord();
        TableBean tablebean = cc.getEntity(rc.getParameterAsString("833"));
        if (tablebean == null)
            return MessageUtils.entityNotFound(EntityType.TABLE.getName(),
                    rc.getParameterAsString("833"));
        if (av.getCode().equals("C") || av.getCode().equals("R")) {
            if (ctx.getRecord().getParameter("850") != null) {// 从列表open
                WorkflowContext host = cc.getWorkflowContext(ctx
                        .getParameterAsString("800"));
                if (host == null)
                    return MessageUtils.contextNotSupport(ctx
                            .getParameterAsString("800"));
                ListContext lc = host.getList(ctx.getParameterAsString("850"));
                if (lc == null)
                    return MessageUtils.dataListNotFound(ctx
                            .getParameterAsString("850"));
                rc = lc.createRecord(RuntimeUtils.createRecord(cc, tablebean,
                        tablebean.isAutoKey()));
                rc.setParameter("814", "C");
                ctx.setRecord(rc);
                if (!Strings.isBlank(lc.getBeforeLogic())) {
                    RecordContext[] rcs = new RecordContext[2];
                    if (!Strings.isBlank(lc.getHost())) {
                        ListContext fc = host.getList(lc.getHost());
                        if (fc == null)
                            return MessageUtils.dataListNotFound(lc.getHost());
                        rcs[0] = fc.getRecord();
                    } else
                        rcs[0] = host.getRecord();
                    rcs[1] = rc;
                    String result = RuntimeUtils.eval(cc, lc.getBeforeLogic(),
                            rcs);
                    if (!result.equals("0000"))
                        return MessageUtils.byErrorCode(cc, host.getRecord(),
                                host.getId(), result);
                }
            } else {// 正常页面
                if (av.getCode().equals("C"))
                    rc.setData(RuntimeUtils.createRecord(cc, tablebean,
                            tablebean.isAutoKey()));
                else if (tablebean.isAutoKey())
                    rc.setValue(tablebean.getKey().get(0), cc.getIdGenerator()
                            .getNextId(tablebean.getId()));
                rc.setParameter("814", "C");
            }
            EventLogic el = RuntimeUtils.castTo(cc, rc, rc.getParameter("835"));
            if (el != null) {
                rc.setParameter("808", Constants.ON_LOAD);
                String result = RuntimeUtils.eval(cc, el, rc);
                if (!result.equals("0000"))
                    return MessageUtils
                            .byErrorCode(cc, rc, ctx.getId(), result);
            }
            Map<String, Object> fields = new HashMap<String, Object>();
            for (String field : av.getFields())
                fields.put(field, rc.getValue(field));
            return new FieldsUpdateResponseMessage(fields);
        } else if (av.getCode().equals("D")) {
            rc.setParameter("814", av.getCode());
            for (ListContext lc : ctx.getLists()) {
                if (lc.getType().equals(Constants.DETAIL)) {
                    List<RecordContext> rcs = lc.getRecords();
                    if (rcs != null) {
                        for (RecordContext r : rcs) {
                            r.setParameter("815", true);
                            if (r.getParameterAsChar("814") == 'C')
                                r.setParameter("814", 'R');
                            else
                                r.setParameter("814", "D");
                        }
                    }
                }
            }
            ctx.commit(cc);
        }
        return new SimpleResponseMessage();
    }

    @Override
    public String getName() {
        return "task.Action";
    }
}
